package ch.silviowangler.hockeygame.service;

import ch.silviowangler.hockeygame.domain.User;
import ch.silviowangler.hockeygame.domain.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author Silvio Wangler
 * @since 1.0
 *        Date: 19.06.2010
 */
@Service("userService")
public class SpringUserService implements MessageSourceAware, UserService {


    private MessageSource messageSource;
    private PasswordEncoder passwordEncoder;
    private UserDao userDao;
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringUserService.class);

    @Autowired
    @Required
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    @Required
    @Autowired
    public void setUserDao(UserDao dao) {
        this.userDao = dao;
    }

    @Override
    public User findUser(String nickName) throws UserNotFoundException {
        throw new UnsupportedOperationException("not yet implemented");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, isolation = Isolation.READ_COMMITTED)
    public User createUser(User user) {

        Assert.notNull(user, "User cannot be null");

        if (LOGGER.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder("About to create user: ");
            sb.append(user.toString());
            LOGGER.debug(sb.toString());
        }

        user.setPassword(this.passwordEncoder.encodePassword(new String(user.getPassword()), null).getBytes());
        return this.userDao.create(user);
    }

    @Override
    public User updateUser(User user) throws UserNotFoundException {
        throw new UnsupportedOperationException("not yet implemented");
    }

    @Override
    public void deleteUser(User user) throws UserNotFoundException {
        throw new UnsupportedOperationException("not yet implemented");
    }

    @Override
    @Required
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}
